﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BUS;
using Public;
using DevExpress.XtraGrid.Views.Grid;

namespace QuanLyKhoHangVatTu
{
    public partial class frmXuatKho : DevExpress.XtraEditors.XtraForm
    {
        XuatKho_BUS xk_bus = new XuatKho_BUS();
        XuatKho_PB xk_pb = new XuatKho_PB();
        int SLTon = 0;
        string mahang = "";
        string kho = "";

        public frmXuatKho()
        {
            InitializeComponent();
        }

        private void labelControl1_Click(object sender, EventArgs e)
        {

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {

        }

        private void frmXuatKho_Load(object sender, EventArgs e)
        {
            cboKhachHang.Properties.DataSource = xk_bus.LayDSKH();
            cboKhachHang.Properties.DisplayMember = "MAKH";
            cboKhachHang.Properties.ValueMember = "TENKH";

            cboNVBanHang.Properties.DataSource = xk_bus.LayDSNV();
            cboNVBanHang.Properties.DisplayMember = "TENNHANVIEN";
            cboNVBanHang.Properties.ValueMember = "MANHANVIEN";

            colMaHang.DataSource = xk_bus.LayDSTonKho();
            colMaHang.DisplayMember = "MAVATTU";
            colMaHang.ValueMember = "MAVATTU";

            colKho.DataSource = xk_bus.LayDSKho();
            colKho.DisplayMember = "TENKHO";
            colKho.ValueMember = "MAKHO";

            

            gridControl1.DataSource = xk_bus.LayDSCTXuat();

            if (Flag_PB.ThemSua == 1)
            {
                txtMa.ResetText();
                cboKhachHang.ResetText();
                txtKhachHang.ResetText();
                txtDiaChi.ResetText();
                txtNguoiNhan.ResetText();
                txtLiDoXuat.ResetText();
                cboNVBanHang.ResetText();
                dtNgayChungTu.ResetText();
                dtNgayHachToan.ResetText();
                try
                {
                    txtMa.Text = xk_bus.NextID_PX();
                }
                catch
                {
                    txtMa.Text = "PX0001";
                }

                EnableEditing(false);
            }
            if (Flag_PB.ThemSua == 2)
            {
                txtMa.Text = XuatKho_PB.MaPX;
                cboKhachHang.SelectedText = XuatKho_PB.MaKH;
                txtKhachHang.Text = XuatKho_PB.TenKH;
                txtNguoiNhan.Text = XuatKho_PB.NguoiNhan;
                txtDiaChi.Text = XuatKho_PB.DiaChi;
                txtLiDoXuat.Text = XuatKho_PB.LyDoXuat;
                cboNVBanHang.EditValue = XuatKho_PB.NhanVien;
                dtNgayHachToan.EditValue = XuatKho_PB.NgayHachToan;
                dtNgayChungTu.EditValue = XuatKho_PB.NgayChungTu;
                gridControl1.DataSource = xk_bus.TimMaPhieuXuat(XuatKho_PB.MaPX);

                EnableEditing(false);
                menuXoa.Enabled = true;

                this.gridView1.NewItemRowText = "Sửa chi tiết nhập kho";
                this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;

                DataRowView row1 = gridView1.GetFocusedRow() as DataRowView;
                if (row1 == null) return;

                SLTon = Int32.Parse(row1["SOLUONG"].ToString());
                mahang = row1["MAHANG"].ToString();
                kho = row1["MAKHO"].ToString();
            }
        }

        private void cboKhachHang_EditValueChanged(object sender, EventArgs e)
        {
            txtKhachHang.Text = cboKhachHang.EditValue.ToString();
        }

        #region "Lấy giá trị"
        private XuatKho_PB GetValues()
        {
            XuatKho_PB.MaPX = txtMa.Text;
            XuatKho_PB.MaKH = cboKhachHang.Text;
            XuatKho_PB.NguoiNhan = txtNguoiNhan.Text;
            XuatKho_PB.DiaChi = txtDiaChi.Text;
            XuatKho_PB.LyDoXuat = txtLiDoXuat.Text;
            XuatKho_PB.NhanVien = cboNVBanHang.EditValue.ToString();
            XuatKho_PB.NgayHachToan = Convert.ToDateTime(dtNgayHachToan.EditValue);
            XuatKho_PB.NgayChungTu = Convert.ToDateTime(dtNgayChungTu.EditValue);
            return xk_pb;
        }
        #endregion

        #region "Enable Controls"
        private void EnableEditing(bool editing)
        {
            menuThem.Enabled = editing;
            menuSua.Enabled = editing;
            menuXoa.Enabled = editing;
            menuLuu.Enabled = !editing;
            menuHoan.Enabled = !editing;
            menuDong.Enabled = !editing;
        }
        #endregion

        #region"Kiểm tra rỗng"
        private bool CheckNull()
        {
            if (txtMa.Text == "" || cboKhachHang.Text == "" || txtKhachHang.Text == "" || txtNguoiNhan.Text == "" || cboNVBanHang.EditValue == "" || dtNgayChungTu.Text == "" || dtNgayHachToan.Text == "")
                return false;
            return true;
        }
        #endregion

        #region "Enable textbox"
        private void EnableTextBox(bool editing)
        {
            txtMa.Enabled = editing;
            cboKhachHang.Enabled = editing;
            txtKhachHang.Enabled = editing;
            txtNguoiNhan.Enabled = editing;
            txtDiaChi.Enabled = editing;
            txtLiDoXuat.Enabled = editing;
            cboNVBanHang.Enabled = editing;
            dtNgayChungTu.Enabled = editing;
            dtNgayHachToan.Enabled = editing;
            gridControl1.Enabled = editing;
        }
        #endregion

        private void menuLuu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gridView1.DataRowCount > 0)
            {
                for (int i = gridView1.RowCount - 1; i >= 0; i--)
                {
                    XuatKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                    XuatKho_PB.MaKho = gridView1.GetRowCellValue(i, "MAKHO").ToString();
                    XuatKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                    XuatKho_PB.ThanhTien = Convert.ToDecimal(gridView1.GetRowCellValue(i, "THANHTIEN").ToString());
                    XuatKho_PB.DonGia = Convert.ToDecimal(gridView1.GetRowCellValue(i, "DONGIA").ToString());
                    if (XuatKho_PB.MaHang == "" || XuatKho_PB.MaKho == "" || XuatKho_PB.SoLuong == "" || XuatKho_PB.ThanhTien.ToString() == "" || XuatKho_PB.DonGia.ToString() == "")
                    {
                        MessageBox.Show("Vui lòng điền đầy đủ thông tin Chi tiết xuất kho", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (xk_bus.CheckExists(XuatKho_PB.MaHang, XuatKho_PB.MaKho))
                    {
                        int sl = xk_bus.LaySLTonKho(XuatKho_PB.MaHang, XuatKho_PB.MaKho);
                        if (sl < Int32.Parse(XuatKho_PB.SoLuong))
                        {
                            MessageBox.Show("Không thể xuất vật tư, hàng hóa <" + XuatKho_PB.MaHang + "> quá số lượng trong tồn kho.\nSố lượng trong tồn kho là: " + sl, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("Không thể xuất vật tư, hàng hóa <" + XuatKho_PB.MaHang + "> quá số lượng trong tồn kho.\nSố lượng trong tồn kho là: 0", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                if (CheckNull())
                {
                    if (Flag_PB.ThemSua == 1)
                    {
                        GetValues();
                        xk_bus.ThemPhieuXuat(xk_pb);
                        for (int i = gridView1.RowCount - 1; i >= 0; i--)
                        {
                            try
                            {
                                XuatKho_PB.ID = xk_bus.NextID_CTX();
                            }
                            catch
                            {
                                XuatKho_PB.ID = "CTX0001";
                            }
                            XuatKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                            XuatKho_PB.MaKho = gridView1.GetRowCellValue(i, "MAKHO").ToString();
                            XuatKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                            XuatKho_PB.ThanhTien = Convert.ToDecimal(gridView1.GetRowCellValue(i, "THANHTIEN").ToString());
                            XuatKho_PB.DonGia = Convert.ToDecimal(gridView1.GetRowCellValue(i, "DONGIA").ToString());

                            xk_bus.ThemCTXuat(xk_pb);
                            int sl = xk_bus.LaySLTonKho(XuatKho_PB.MaHang, XuatKho_PB.MaKho);
                            int a = 0;
                            a = sl - Int32.Parse(XuatKho_PB.SoLuong);
                            XuatKho_PB.SoLuong = a.ToString();
                            xk_bus.SuaTonKho(xk_pb);
                        }
                    }
                    if (Flag_PB.ThemSua == 2)
                    {
                        GetValues();
                        xk_bus.SuaPhieuXuat(xk_pb);
                        for (int i = gridView1.RowCount - 1; i >= 0; i--)
                        {
                            XuatKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                            XuatKho_PB.MaKho = gridView1.GetRowCellValue(i, "MAKHO").ToString();
                            XuatKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                            XuatKho_PB.ThanhTien = Convert.ToDecimal(gridView1.GetRowCellValue(i, "THANHTIEN").ToString());
                            XuatKho_PB.DonGia = Convert.ToDecimal(gridView1.GetRowCellValue(i, "DONGIA").ToString());
                            XuatKho_PB.ID = gridView1.GetRowCellValue(i, "ID").ToString();
                            xk_bus.SuaCTXuat(xk_pb);
                            if (xk_bus.CheckExists(XuatKho_PB.MaHang, XuatKho_PB.MaKho))
                            {
                                if (mahang != XuatKho_PB.MaHang || kho != XuatKho_PB.MaKho)
                                {
                                    int sl = xk_bus.LaySLTonKho(XuatKho_PB.MaHang, XuatKho_PB.MaKho);
                                    sl -= Int32.Parse(XuatKho_PB.SoLuong);
                                    XuatKho_PB.SoLuong = sl.ToString();
                                    xk_bus.SuaTonKho(xk_pb);
                                    XuatKho_PB.SoLuong = gridView1.GetRowCellValue(i, "SOLUONG").ToString();
                                    int sl1 = xk_bus.LaySLTonKho(mahang, kho);
                                    sl1 = sl1 + SLTon;
                                    XuatKho_PB.SoLuong = sl1.ToString();
                                    XuatKho_PB.MaHang = mahang;
                                    XuatKho_PB.MaKho = kho;
                                    xk_bus.SuaTonKho(xk_pb);
                                }
                                else
                                {
                                    XuatKho_PB.MaHang = gridView1.GetRowCellValue(i, "MAHANG").ToString();
                                    XuatKho_PB.MaKho = gridView1.GetRowCellValue(i, "MAKHO").ToString();
                                    int sl = xk_bus.LaySLTonKho(XuatKho_PB.MaHang, XuatKho_PB.MaKho);
                                    if (SLTon > Int32.Parse(XuatKho_PB.SoLuong))
                                    {
                                        SLTon -= Int32.Parse(XuatKho_PB.SoLuong);
                                        sl = xk_bus.LaySLTonKho(XuatKho_PB.MaHang, XuatKho_PB.MaKho);
                                        sl += SLTon;
                                        XuatKho_PB.SoLuong = sl.ToString();
                                        xk_bus.SuaTonKho(xk_pb);
                                    }
                                    else
                                    {

                                        int a = Int32.Parse(XuatKho_PB.SoLuong);
                                        a -= SLTon;
                                        int sl1 = xk_bus.LaySLTonKho(XuatKho_PB.MaHang, XuatKho_PB.MaKho);
                                        sl1 -= a;
                                        XuatKho_PB.SoLuong = sl1.ToString();
                                        xk_bus.SuaTonKho(xk_pb);
                                    }
                                }
                            }
                            else
                            {

                            }
                            
                        }
                    }
                    menuThem.Enabled = true;
                    menuSua.Enabled = false;
                    menuXoa.Enabled = false;
                    menuLuu.Enabled = false;
                    menuHoan.Enabled = false;
                    menuDong.Enabled = true;
                    EnableTextBox(false);
                    txtMa.Enabled = false;
                }
            }
            else
            {
                MessageBox.Show("Vui lòng điền đầy đủ thông tin Chi tiết xuất kho", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void menuHoan_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            frmXuatKho_Load(sender, e);
        }

        private void menuDong_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DialogResult = DialogResult.OK;
            this.Close();
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            //if (Flag_PB.ThemSua == 2)
            //{
            //    XuatKho_PB.ID = xk_bus.NextID_CTX();
            //    XuatKho_PB.MaHang = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "MAHANG").ToString();
            //    XuatKho_PB.MaKho = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "MAKHO").ToString();
            //    XuatKho_PB.SoLuong = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "SOLUONG").ToString();
            //    XuatKho_PB.ThanhTien = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "THANHTIEN").ToString();
            //    XuatKho_PB.DonGia = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "DONGIA").ToString();               
            //    ////Kiểm tra đây là dòng dữ liệu mới hay cũ, nếu là mới thì mình insert
            //    GridView view = sender as GridView;
            //    if (view.IsNewItemRow(e.RowHandle))
            //        xk_bus.ThemCTXuat(xk_pb);
            //}
        }

        private void gridView1_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            DataRowView row = gridView1.GetFocusedRow() as DataRowView;
            if (row == null) return;

            row["SOLUONG"] = 1;
            row["DONGIA"] = 0;
        }

        private void colMaHang_EditValueChanged(object sender, EventArgs e)
        {
            var lkpMaHang = sender as LookUpEdit;
            if (lkpMaHang == null) return;

            DataRow row = gridView1.GetFocusedDataRow();
            if (row == null) return;

            // tim ten hang rồi gán cho row["tenhang"]
            DataTable dtVattu = lkpMaHang.Properties.DataSource as DataTable;
            if (dtVattu == null) return;

            dtVattu.PrimaryKey = new DataColumn[] { dtVattu.Columns["MAVATTU"] };
            DataRow vattu = dtVattu.Rows.Find(lkpMaHang.EditValue);
            if (vattu == null) return;

            row["TENVATTU"] = vattu["TENVATTU"];
            row["DIENGIAI"] = vattu["DIENGIAI"];
            row["DONGIA"] = vattu["DONGIABAN"];
        }

        private void menuXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (MessageBox.Show("Bạn có thực sự muốn xóa (những) dòng đã chọn không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                for (int i = gridView1.GetSelectedRows().Length - 1; i >= 0; i--)
                {
                    XuatKho_PB.ID = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[i], "ID").ToString();
                    xk_bus.XoaCTXuat(xk_pb);
                }
                gridControl1.DataSource = xk_bus.TimID(xk_pb);
            }
        }

        private void menuThem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Flag_PB.ThemSua = 1;
            txtMa.ResetText();
            txtDiaChi.ResetText();
            txtNguoiNhan.ResetText();
            txtLiDoXuat.ResetText();
            cboNVBanHang.ResetText();
            dtNgayChungTu.ResetText();
            dtNgayHachToan.ResetText();

            EnableEditing(false);
            EnableTextBox(true);

            txtMa.Text = xk_bus.NextID_PX();

            gridControl1.DataSource = xk_bus.LayDSCTXuat();

            this.gridView1.NewItemRowText = "Click để thêm 1 dòng mới";
            this.gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.True;
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            DataRow chiTiet = gridView1.GetFocusedDataRow();
            if (chiTiet == null) return;

            chiTiet["THANHTIEN"] = Convert.ToDecimal(chiTiet["SOLUONG"]) * Convert.ToDecimal(chiTiet["DONGIA"]);
        }
    }
}